#! /usr/bin/env python
# -*- coding: UTF-8 -*-
import datetime
import requests


class SendWeiXinWork:
    def __init__(self):
        self.CORP_ID = "wweb5e85354e724189"  # 企业号的标识
        self.SECRET = "d227B33SVo_zu43BNWsaVLoc0qxkjGaNcbEWllzeXGE"  # 管理组凭证密钥
        self.AGENT_ID = 1000005  # 应⽤ID
        self.token = self.get_token()

    def get_token(self):
        url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken"
        data = {"corpid": self.CORP_ID, "corpsecret": self.SECRET}
        req = requests.get(url=url, params=data)
        res = req.json()
        if res["errmsg"] == "ok":
            return res["access_token"]
        else:
            return res

    def send_message(self, to_user, context):
        time_1 = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=%s" % self.token
        data = {
            "touser": "21100351",  # 发送个⼈就填⽤户账号
            # "toparty": 5,  # 发送组内成员就填部门ID
            "msgtype": "textcard",
            "agentid": self.AGENT_ID,
            "textcard": {
                "title": "【测试】温湿度报警通知",
                "description": "<div class='gray'>{}</div> "
                "<div class='normal'>实验室温湿度超出监控区间，温度为{}<br>请确认并寻找维修支持！</div>"
                "<div class='highlight'>公用维修电话：023-63985950</div>".format(time_1, context),
                "url": "http://10.64.35.51/",
                "btntxt": "更多",
            },
            "safe": "0",
        }
        req = requests.post(url=url, json=data)
        res = req.json()
        if res["errmsg"] == "ok":
            print("send message sucessed")
            return "send messaged e sucessed"
        else:
            return res


if __name__ == "__main__":
    SendWeiXinWork = SendWeiXinWork()
    SendWeiXinWork.send_message("2")
